<?php

namespace frontendm\models;

/**
 * @author  shuang
 * @date    2016-8-22 14:40:38
 * @version V1.0
 * @desc    
 */
use common\models\Cart;
use yii\behaviors\TimestampBehavior;
use common\components\MTools;
use Yii;

class WB_Cart extends Cart {
    /*
     * 设置表操作行为动作
     * return array
     */

    public function behaviors() {
        return[
            [
                'class' => TimestampBehavior::className()
            ]
        ];
    }

    /*
     * 关联购物车类型
     */

    public function getTypeCart() {

        return $this->hasOne(WB_Dictionary::className(), ['id' => 'cart_type']);
    }
    /*
     * 关联商品
     */
    public function getProPid(){
        return $this->hasOne(WB_Product::className(), ['id' => 'pid']);
    }

    /*
     * 插入、更新数据
     * @params $data array
     * @params $id int 主键
     * return boolean 
     */

    public static function createData($id = null) {
        $model = $id ? WB_Cart::findOne($id) : new WB_Cart();
        try {
            $pid = Yii::$app->request->get("pid");
            if ($pid) {
                if (Yii::$app->user->id) {
                    $condition = "pid='$pid' and userid=" . Yii::$app->user->id;
                } else {
                    $condition = "pid='$pid' and sessionid='" . Yii::$app->session->getId() . "'";
                }
                //查询商品是否已加入购物车
                $good = WB_Cart::find()->where($condition)->one();
                if ($good instanceof WB_Cart) {
                    $good->product_num = $good->product_num + 1;
                    return $good->update();
                } else {
                    $res = WB_Product::find()->where("id='$pid'")->with(["unitType", "cidType","dStandard"])->one();
                    $model->userid = Yii::$app->user->id;
                    $model->sessionid = Yii::$app->session->getId();
                    $model->pid = $res->id;
                    $model->product_name = $res->name;
                    $model->sale_price = $res->sale_price;
                    $model->coupon_price = $res->coupon_price;
                    $model->product_num = Yii::$app->request->get("pnum");
                    $model->cart_type = 0;
                    $model->is_gife = 0;
                    $model->unitname = $res->unitType->name;
                    $model->standard = $res->dStandard ? $res->dStandard->name : null;
                    $model->proimage = $res->image;
                    return $model->save();
                }
            }
        } catch (Exception $e) {
            throw $e;
        }
    }
    //购物车商品数量
    public static function pronum(){
        if(Yii::$app->user->id){
            $condition = "userid=".Yii::$app->user->id;
        }else{
            $condition = "sessionid='".Yii::$app->session->getId()."'";
        }
        return WB_Cart::find()->where($condition)->count();
    } 

}
